#include "archwiki.h"

#include <httpclient.h>

ArchWiki::ArchWiki(Type type) : m_type(type)
{

}

QString ArchWiki::name()
{
    switch (m_type) {
    case Normal:
        return "Arch Wiki - 搜索";
    case Api:
        return "Arch Wiki - API";
    }
}

// Only Normal
QString ArchWiki::prefix()
{
    return "https://wiki.archlinuxcn.org/wiki/";
}

QList<QListWidgetItem *> ArchWiki::searching_item(const QString &text)
{
    QList<QListWidgetItem *> list;

    if (m_type == Normal) {
        Request req("https://wiki.archlinuxcn.org/wzh/rest.php/v1/search/title");
        req.addQuery("q", text);
        req.addQuery("limit", "100");
        auto pages = HttpClient::instance().get(req).toMap().value("pages").toList();
        foreach (auto page, pages) {
            auto id = page.toMap().value("id").toInt();
            auto key = page.toMap().value("key").toString();
            auto title = page.toMap().value("title").toString();
            auto excerpt = page.toMap().value("excerpt").toString();
            auto matched_title = page.toMap().value("matched_title").toString();
            auto description = page.toMap().value("description").toString();
            auto thumbnail = page.toMap().value("thumbnail").toString();

            auto item = newItem();
            item->setText(title);
            item->setData(990, key);
            list << item;
        }
    } else {
        Request req("https://wiki.archlinuxcn.org/wzh/api.php");
        req.addQuery("action", "opensearch");
        req.addQuery("format", "json");
        req.addQuery("formatversion", "2");
        req.addQuery("search", text.isEmpty() ? "ArchWiki" :  text);
        req.addQuery("namespace", "0");
        req.addQuery("limit", "100");
        auto values = HttpClient::instance().get(req).toList();


        if (values.count() == 4) {
            auto search = values.at(0).toString();
            auto titles = values.at(1).toList();
            auto unkonw =  values.at(2).toList();
            auto links = values.at(3).toList();

            for (int i = 0; i < links.count(); ++i) {
                auto title = titles.at(i).toString();
                auto link = links.at(i).toString();

                auto item = newItem();
                item->setText(title);
                item->setData(990, link);
                list << item;
            }
        }
    }


    if (list.count() == 0) {
        auto item = newItem();
        item->setText("提示: 没有结果");
        list << item;
    }

    return list;
}

QString ArchWiki::content_item(const QListWidgetItem *item)
{
    switch (m_type) {
    case Normal:
        return prefix() + item->data(990).toString();
    case Api:
        return item->data(990).toString();
    }
}
